/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gameheart.client.logic;

import gameheart.client.sprite.SynMessage;
import gameheart.client.sprite.ImageResposity;
import gameheart.client.sprite.ImageSprite;
import gameheart.client.sprite.LabelSprite;
import gameheart.client.sprite.Sprite;
import gameheart.client.sprite.TextBoxSprite;
import gameheart.transport.MyException;
import gameheart.transport.NetworkTransporter;
import gameheart.transport.Transporter;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author win7
 */
public class JoinState extends  State {


   JoinState(MainGame mainGame) {
       super(mainGame);
    }
    private volatile int _menuSelectedIndex = -1;

    public void gameUpdate() {
        if (_menuSelectedIndex > -1) {
            try {
                MenuClick(_menuSelectedIndex);
            } catch (MyException ex) {
                Logger.getLogger(CreateGameState.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnknownHostException ex) {
                Logger.getLogger(CreateGameState.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    ImageSprite _bg;
    public void gameRender(Graphics g) {
       _bg.draw(g);
       for(int index = 0; index < _labelSprite.size(); ++index)
       {
           _labelSprite.get(index).draw(g);
       }
       for(int index = 0; index < _userInputSprite.size();++index)
       {
           _userInputSprite.get(index).draw(g);
       }
       for(int index = 0; index < menu.size(); ++index)
       {
           menu.get(index).draw(g);
       }

    }
    Image background;
    //ArrayList<Sprite> sprite = new ArrayList<Sprite>();
    ArrayList<LabelSprite> menu = new ArrayList<LabelSprite>();
    ArrayList<TextBoxSprite> _userInputSprite = new ArrayList<TextBoxSprite>();
    ArrayList<LabelSprite> _labelSprite = new ArrayList<LabelSprite>();
    int maxInput = 14;

    public void gameInit() {
        imageResposity = new ImageResposity();
        _bg = new ImageSprite(0, 0, 1024, 708, imageResposity, "bg_main.jpg");
        background = imageResposity.getImage("bg_main.jpg");
        BufferedImage labelBg = imageResposity.getImage("menu.jpg");
        BufferedImage textBoxBg = imageResposity.getImage("NewTextBox.jpg");
        _labelSprite.add(new LabelSprite(100, 300, 125, 30, "Địa chỉ máy chủ : ",labelBg ));
       // sprite.add(_labelSprite.get(_labelSprite.size() - 1));
//        _labelText.add("Địa chỉ máy chủ :");
        _userInputSprite.add(new TextBoxSprite(400, 300, 175, 30, "localhost",maxInput, textBoxBg));
       // sprite.add(_userInputSprite.get(_userInputSprite.size() - 1));
//        _userInputString.add(new SynMessage(maxInput, "localhost"));

        _labelSprite.add(new LabelSprite(100, 400, 125, 30, "Port : ", labelBg));
       // sprite.add(_labelSprite.get(_labelSprite.size() - 1));
////        _labelText.add("Port :");
        _userInputSprite.add(new TextBoxSprite(400, 400, 175, 30, "9876",maxInput, textBoxBg));
      //  sprite.add(_userInputSprite.get(_userInputSprite.size() - 1));
//        _userInputString.add(new SynMessage(maxInput, "9876"));

        _labelSprite.add(new LabelSprite(100, 500, 125, 30, "User name : ", labelBg));
       // sprite.add(_labelSprite.get(_labelSprite.size() - 1));
       // _labelText.add("Use name :");
        _userInputSprite.add(new TextBoxSprite(400, 500, 175, 30,"", maxInput, textBoxBg));
       // sprite.add(_userInputSprite.get(_userInputSprite.size() - 1));
      //  _userInputString.add(new SynMessage(maxInput, "ab"));

       // Sprite menuitems = new ImageSprite(750, 340, 100, 40, imageResposity, "menu.jpg");
        menu.add(new LabelSprite(800, 425, 200, 30, "Join", labelBg));
//        menu.add(new Sprite(800, 465, 200, 30, images, "menu.jpg"));
//        menu.add(new Sprite(800, 505, 200, 30, images, "menu.jpg"));
        menu.add(new LabelSprite(800, 545, 200, 30, "Back", labelBg));
       // menuitem.add("Join");
//        menuitem.add("Option");
//        menuitem.add("Help");
       // menuitem.add("Back");
       
    }

    private void ProcessMouseClick(MouseEvent e) {
        Rectangle mouseRect = new Rectangle(e.getX(), e.getY(), 5, 5);
        for (Sprite currentSpirite : _userInputSprite) {
            Rectangle rect = new Rectangle(currentSpirite.getX(), currentSpirite.getY() + 30, currentSpirite.getWidth(), currentSpirite.getHeight());
            if (mouseRect.intersects(rect)) {
                currentGetInputIndex = _userInputSprite.indexOf(currentSpirite);
                break;
            } else {
                currentGetInputIndex = -1;
            }
        }
        for (Sprite currentSpirite : menu) {

            Rectangle rect = new Rectangle(currentSpirite.getX(), currentSpirite.getY() + 30, currentSpirite.getWidth(), currentSpirite.getHeight());
            if (mouseRect.intersects(rect)) {
                _menuSelectedIndex = menu.indexOf(currentSpirite);
                break;
            }
        }

    }
    private ImageResposity imageResposity;

    private void MenuClick(int menuIndex) throws MyException, UnknownHostException {
        switch (menuIndex) {
            case 0: {
                String userName = _userInputSprite.get(2).getText().getMessage();
                if (userName.length() > 0) {
                    String serverIP = _userInputSprite.get(0).getText().getMessage();
                    int serverPort = -1;
                    try {
                        serverPort = Integer.parseInt(_userInputSprite.get(1).getText().getMessage());
                    } catch (NumberFormatException ex) {
                        Logger.getLogger(JoinState.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    ClientAdapter adapter = null;
                    Socket socket = null;
                    try {
                        socket = new Socket(serverIP, serverPort);
                    } catch (IOException ex) {
                        Logger.getLogger(JoinState.class.getName()).log(Level.SEVERE, null, ex);
                        return;
                    }
                    Transporter transporter = new NetworkTransporter(socket);
                    adapter = new ClientAdapter(transporter);
                    _mainGame.setAdapter(adapter);
                    adapter.joinGame(userName);
                    _mainGame.ChangeGameState(GameStateIds.WaitUserStateId);
                }
                break;
            }
            case 1: {
                _mainGame.ChangeGameState(GameStateIds.MenuStateId);
                break;
            }
        }
        _menuSelectedIndex = -1;
    }

    private void ProcessKey(KeyEvent e) {
        if (e != null) {
            int keyCode = e.getKeyCode();
            if (currentGetInputIndex >= 0) {
                if(keyCode == KeyEvent.VK_ENTER)
                {
                    return;
                }
                if (keyCode == KeyEvent.VK_BACK_SPACE) {
                    _userInputSprite.get(currentGetInputIndex).getText().removeChar();
                } else {
                    if (e.getKeyChar() != KeyEvent.CHAR_UNDEFINED) {
                        _userInputSprite.get(currentGetInputIndex).getText().addChar(e.getKeyChar());
                    }
                }
            }
        }
    }
    volatile private int currentGetInputIndex = -1;

    public void gameEnd() {
    }

    public void mouseClicked(MouseEvent e) {
        ProcessMouseClick(e);
    }

    public void keyPressed(KeyEvent e) {
        ProcessKey(e);
    }
}
